package com.hp.gxw.u8;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.hp.gxw.u8.dto.U8ApiResultDto;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;

@Component
@Slf4j
public class U8ApiUtils {
	
	@Value("${u8client.httpUrl}")
	private String api_url;
	
	public U8ApiResultDto httpRequest(String param) {
		/** 网络的url地址 */
		URL url = null;
		HttpURLConnection httpUrlConnection = null ;
		DataOutputStream  out = null; //写DataOutputStream
		InputStream inputStream = null; //读
		BufferedReader in = null;
		StringBuilder result = new StringBuilder();
		U8ApiResultDto u8ApiResultDto = null;
		try {
			byte[] bytes = param.getBytes("UTF-8");
			url = new URL(api_url);
			httpUrlConnection = (HttpURLConnection) url.openConnection();
			httpUrlConnection.setConnectTimeout(10000);
//			httpUrlConnection.setReadTimeout(10000);
			httpUrlConnection.setRequestMethod("POST");
			// Post 请求不能使用缓存
			httpUrlConnection.setUseCaches(false);
			httpUrlConnection.setRequestProperty("Connection", "Keep-Alive");//维持长连接  
			httpUrlConnection.setRequestProperty("Charset", "UTF-8"); 
			httpUrlConnection.setRequestProperty("Content-Length", String.valueOf(bytes.length)); 
			httpUrlConnection.setRequestProperty("Content-Type", "text/xml; charset=UTF-8"); 
			httpUrlConnection.setRequestProperty("Accept", "text/xml");
			//传入参数
			if(StringUtils.isNotEmpty(param)) {
				httpUrlConnection.setDoOutput(true);
				out = new DataOutputStream(httpUrlConnection.getOutputStream());
				out.write(bytes);
				out.flush();
		        out.close();
			}
			inputStream = httpUrlConnection.getInputStream();

			in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
			String res;
			while ((res = in.readLine()) != null) {
				result.append(res);
			}
			log.info("返回结果-----------------"+result);
			if(StringUtils.isNotEmpty(result)) {
				Document document=DocumentHelper.parseText(result.toString());
				Element root = document.getRootElement();//得到根结点
				u8ApiResultDto = new U8ApiResultDto();
				u8ApiResultDto.setXml(result.toString());
				//特殊处理存货档案查询
				for (Iterator i = root.elementIterator(); i.hasNext();) {
					Element element = (Element) i.next();
					if(element.getName().equals("Inventory")){
						for (Iterator i1 = element.elementIterator(); i1.hasNext();) {
							Element element1 = (Element) i1.next();
							if(element1.getName().equals("header")){
								for (Iterator i2 = element1.elementIterator(); i2.hasNext();) {
									Element element2 = (Element) i2.next();
									System.out.println(element2.getName());
									if(element2.getName().equals("unitgroup_code")){
										u8ApiResultDto.setCgroupcode(element2.getText());
									}
								}
							}
						}
					}
				}
				u8ApiResultDto.setCode(root.attributeValue("succeed"));
				u8ApiResultDto.setMsg(root.attributeValue("dsc"));
				u8ApiResultDto.setRetid(root.attributeValue("retid"));
				u8ApiResultDto.setRetcode(root.attributeValue("retcode"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			httpUrlConnection.disconnect();
		}
		return u8ApiResultDto;
	}
	
//	public static void main(String[] args) {
//		StringBuilder sb = new StringBuilder();
//		sb.append("<?xml version='1.0' encoding='UTF-8' standalone='yes'?>");
//		sb.append("<ufinterface efserverid='EF_997' eftype='24' proc='add' efdebug='1' actions='add' ddate='2021-05-02'>");
//		sb.append("   <voucher xmlns:z='EF' cardnumber='24' ccardname=''>");
//		sb.append("        <head>");
//		sb.append("            <z:row cvouchtype='01' cbustype='普通采购' csource='存货' cwhcode='01' ccode='0000000001' ddate='2021-05-02' cmaker='刘红菊' iexchrate='1.0' dnmaketime='2022-03-02T21:25:30' cexch_name='人民币' vt_id='89'/>");
//		sb.append("        </head>");
//		sb.append("        <body>");
//		sb.append("            <z:row cinvcode='204051' iquantity='1.0' iunitcost='1.0' iprice='1' iaprice='1' ioritaxcost='1.0' ioricost='1.0' iorimoney='1' iorisum='1' itaxrate='0.0' isum='1' irowno='1'/>");
//		sb.append("        </body>");
//		sb.append("   </voucher>");
//		sb.append("</ufinterface>");
////		U8ApiResultDto httpRequest = httpRequest("<ufinterface efserverid='EF_997' eftype='24' proc='query'></ufinterface>");
////		U8ApiResultDto httpRequest = httpRequest(sb.toString());
////		U8ApiResultDto httpRequest = httpRequest("<ufinterface efserverid='EF_997' eftype='24' proc='add' efdebug='1' actions='add' ddate='2021-05-02'><head><z:row cvouchtype='01' cbustype='普通采购' csource='存货' cwhcode='01' ccode='0000000001' ddate='2021-05-02' cmaker='刘红菊' iexchrate='1.0' dnmaketime='2022-03-02T21:25:30' cexch_name='人民币' vt_id='89'/></head><body><z:row cinvcode='204051' iquantity='1.0' iunitcost='1.0' iprice='1' iaprice='1' ioritaxcost='1.0' ioricost='1.0' iorimoney='1' iorisum='1' itaxrate='0.0' isum='1' irowno='1'/></body></ufinterface>");
//		
//		// 1、创建document对象
//		Document document = DocumentHelper.createDocument();
//		// 2、创建根节点rss
//		Element ufinterface = document.addElement("ufinterface");
//		ufinterface.addNamespace("z", "http://www.w3.org/2001/XMLSchema");
//		// 向ufinterface节点添加efserverid属性(U8账套)
//		ufinterface.addAttribute("efserverid", "EF_997");
//		// 向ufinterface节点添加eftype属性(方法：24代表采购入库)
//		ufinterface.addAttribute("eftype", "24");
//		// 向ufinterface节点添加proc属性(增删改查事件)
//		ufinterface.addAttribute("proc", "add");
//		// 向ufinterface节点添加efdebug属性
//		ufinterface.addAttribute("efdebug", "1");
//		// 向ufinterface节点添加actions属性,入库后自动审核
////					ufinterface.addAttribute("actions", "verify");
//		ufinterface.addAttribute("actions", "add");
//		ufinterface.addAttribute("ddate", "2021-05-02");
//		// 4、生成子节点及子节点内容
//		Element voucher = ufinterface.addElement("voucher");
//		voucher.addAttribute("cardnumber", "24");
//		voucher.addAttribute("ccardname", "");
//		voucher.addNamespace("z", "EF");
//		Element head = voucher.addElement("head");
//		Element headRow = head.addElement("z:row");
//		headRow.addAttribute("cvouchtype", "01");// 传入参数：单据类型
//		headRow.addAttribute("cbustype", "普通采购");// 传入参数
//		headRow.addAttribute("csource", "存货");// 传入参数
//		headRow.addAttribute("cwhcode", "01");// 传入参数：仓库
//		headRow.addAttribute("ccode", "0000000001");// 传入参数：到货单号
//		headRow.addAttribute("ddate", "2021-05-02");// 传入参数：入库日期
//		headRow.addAttribute("cmaker", "刘红菊");// 传入参数：制单人
//		headRow.addAttribute("iexchrate", "1.0");// 传入参数：汇率
//		headRow.addAttribute("dnmaketime", "2022-03-02T21:25:30");// 传入参数：制单日期
//		headRow.addAttribute("cexch_name", "人民币");// 传入参数：制单日期
//		headRow.addAttribute("vt_id", "89");// 传入参数：单据模板号
//		Element body = voucher.addElement("body");
//		Element bodyRow = body.addElement("z:row");
//		bodyRow.addAttribute("cinvcode", "204051");// 传入参数：存货编码
//		bodyRow.addAttribute("iquantity", "1");// 传入参数：数量
//		bodyRow.addAttribute("iunitcost", "1");// 传入参数：采购订单号
//		bodyRow.addAttribute("iprice", "1");// 传入参数：采购订单号
//		bodyRow.addAttribute("iaprice", "1");// 传入参数：采购订单号
//		bodyRow.addAttribute("ioritaxcost", "1");// 传入参数：采购订单号
//		bodyRow.addAttribute("ioricost", "1");// 传入参数：采购订单号
//		bodyRow.addAttribute("iorimoney", "1");// 传入参数：采购订单号
//		bodyRow.addAttribute("ioritaxprice", "1");// 传入参数：采购订单号
//		bodyRow.addAttribute("iorisum", "1");// 传入参数：采购订单号
//		bodyRow.addAttribute("itaxrate", "0.0");// 传入参数：采购订单号
//		bodyRow.addAttribute("itaxprice", "1");// 传入参数：采购订单号
//		bodyRow.addAttribute("isum", "1");// 传入参数：采购订单号
//		bodyRow.addAttribute("irowno", String.valueOf(1));// 行号
//		
//		U8ApiResultDto httpRequest = httpRequest(document.asXML().split("\n")[1]);
//		
//		System.out.println(httpRequest.getCode());
//		System.out.println(httpRequest.getMsg());
//		System.out.println(httpRequest.getRetid());
//	}
}
